package com.zyb.warehouse.service.impl;

import com.zyb.warehouse.common.Result;
import com.zyb.warehouse.dto.AssignRoleDto;
import com.zyb.warehouse.dto.Page;
import com.zyb.warehouse.entity.CurrentUser;
import com.zyb.warehouse.entity.Role;
import com.zyb.warehouse.entity.User;
import com.zyb.warehouse.entity.UserRole;
import com.zyb.warehouse.mapper.LoginMapper;
import com.zyb.warehouse.mapper.RoleMapper;
import com.zyb.warehouse.mapper.UserMapper;
import com.zyb.warehouse.mapper.UserRoleMapper;
import com.zyb.warehouse.service.UserService;
import com.zyb.warehouse.utils.DigestUtil;
import com.zyb.warehouse.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Description:用户管理业务逻辑实现
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 分页查询用户
     *
     * @param page
     * @param user
     * @return
     */
    public Page queryPageUser(Page page, User user) {
        int count = userMapper.selectUserCount(user);
        List<User> userList = userMapper.selectUserPage(page, user);
        page.setTotalNum(count);
        page.setResultList(userList);
        return page;
    }

    /**
     * 添加用户
     *
     * @param user
     * @param token
     * @return
     */
    @Transactional
    public Result addUser(User user, String token) {
        //查询账号是否存在
        User u = loginMapper.selectUserByCode(user.getUserCode());
        if (u != null) {
            return Result.err(Result.CODE_ERR_BUSINESS, "账号已存在");
        }
        //密码进行加密
        String pwd = DigestUtil.hmacSign(user.getUserPwd());
        //从前端获取添加人的ID
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //给用户赋值
        user.setUserPwd(pwd);
        user.setCreateBy(currentUser.getUserId());
        //进行添加
        Integer flag = userMapper.insertUser(user);
        if (flag > 0) {
            return Result.ok("添加用户成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加用户失败");
    }

    /**
     * 用户启用或者禁用
     *
     * @param user
     * @param token
     * @return
     */
    @Transactional
    public Result userStartOrStop(User user, String token) {
        //从前端获取修改人的ID
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        user.setUpdateBy(currentUser.getUserId());
        user.setUpdateTime(new Date());

        Integer i = userMapper.updateUser(user);
        if (i > 0) {
            return Result.ok("启用或禁用成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "启用或禁用失败");
    }

    /**
     * 根据用户ID查询用户对应的角色
     *
     * @param userId
     * @return
     */
    public List<Role> queryUserRoleByUserId(Integer userId) {
        return userMapper.selectUserRoleByUserId(userId);
    }

    /**
     * 给用户分配角色
     *
     * @param assignRoleDto
     */
    @Transactional
    public void userAssignRole(AssignRoleDto assignRoleDto) {
        //先删除原有的角色
        userRoleMapper.deleteUserRoleByUserId(assignRoleDto.getUserId());
        List<String> roleCheckList = assignRoleDto.getRoleCheckList();
        for (String roleName : roleCheckList) {
            //根据角色名字查询角色ID
            Integer roleId = roleMapper.selectRoleIdByRoleName(roleName);
            //封装每一个用户角色对象
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleId);
            userRole.setUserId(assignRoleDto.getUserId());
            //分配角色
            userRoleMapper.insertUserRole(userRole);
        }
    }

    /**
     * 修改用户
     *
     * @param user
     * @param token
     * @return
     */
    public Result modifyUser(User user, String token) {
        //从前端获取修改人的ID
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //设置属性
        user.setUpdateBy(currentUser.getUserId());
        user.setUpdateTime(new Date());

        Integer i = userMapper.updateUser(user);
        if (i > 0) {
            return Result.ok("修改成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "修改失败");
    }

    /**
     * 删除用户
     *
     * @param userIds
     * @return
     */
    @Transactional
    public Result removeUser(List<Integer> userIds) {
        //先删除用户角色表里的关系
        for (Integer userId : userIds) {
            userRoleMapper.deleteUserRoleByUserId(userId);
        }
        //然后进行逻辑删除
        Integer i = userMapper.deleteUser(userIds);
        if (i > 0) {
            return Result.ok("删除用户成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "删除用户失败");
    }

    /**
     * 重置密码(123456)
     *
     * @param userId
     * @return
     */
    @Transactional
    public Result restPassword(Integer userId, String token) {
        //从前端获取修改人的ID
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        //重置密码
        String password = DigestUtil.hmacSign("123456");
        //设置属性
        User user = new User();
        user.setUserId(userId);
        user.setUserPwd(password);
        user.setUpdateTime(new Date());
        user.setUpdateBy(currentUser.getUserId());
        //重置
        Integer i = userMapper.updateUser(user);
        if (i > 0) {
            return Result.ok("重置密码成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "重置密码失败");
    }
}
